<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/gmxs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/gmxs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/gmxs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/gmxs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/gmxs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/gmxs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/gmxs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java," />





  <link rel="alternate" href="/gmxs/atom.xml" title="葛木小舍先生的博客" type="application/atom+xml" />






<meta name="description" content="今天,准备填完昨天没填的坑,将排序算法方面的知识系统的学习一下,但是在简单的了解了一下后,有些不知如何组织学习了,因为排序算法的种类,实在是太多了,各有优略,各有适用的场景.有些不知所措,从何开始.">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="排序算法的简单认识">
<meta property="og:url" content="http://yoursite.com/2019/04/07/java初探/排序方法的简单认识/index.html">
<meta property="og:site_name" content="葛木小舍先生的博客">
<meta property="og:description" content="今天,准备填完昨天没填的坑,将排序算法方面的知识系统的学习一下,但是在简单的了解了一下后,有些不知如何组织学习了,因为排序算法的种类,实在是太多了,各有优略,各有适用的场景.有些不知所措,从何开始.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-f8ccb3215bc1d12b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-1df19b8c4a8ce91e.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-a9b95c7a5b6a1942.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-30399c0701a1b5f8.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-efe0b0138af44107.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-18bed0b197f975a4.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-a2d18a648ec93b88.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/8067684-495d11fd76ed4e9d.gif?imageMogr2/auto-orient/strip">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-22a7e96231e8ef1b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-04-14T07:27:41.564Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="排序算法的简单认识">
<meta name="twitter:description" content="今天,准备填完昨天没填的坑,将排序算法方面的知识系统的学习一下,但是在简单的了解了一下后,有些不知如何组织学习了,因为排序算法的种类,实在是太多了,各有优略,各有适用的场景.有些不知所措,从何开始.">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/8067684-f8ccb3215bc1d12b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/gmxs/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/07/java初探/排序方法的简单认识/"/>





  <title>排序算法的简单认识 | 葛木小舍先生的博客</title>
  









  
  <script type="text/javascript"
  color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>


	<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/gmxs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">葛木小舍先生的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/gmxs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/gmxs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/gmxs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/gmxs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/gmxs/2019/04/07/java初探/排序方法的简单认识/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="葛木小舍先生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/gmxs/images/touxiang.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="葛木小舍先生的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">排序算法的简单认识</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-07T00:00:00+08:00">
                2019-04-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/gmxs/categories/Java初探/" itemprop="url" rel="index">
                    <span itemprop="name">Java初探</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/gmxs/2019/04/07/java初探/排序方法的简单认识/" class="leancloud_visitors" data-flag-title="排序算法的简单认识">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
			 <span>℃</span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6,036
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  25
                </span>
              
            </div>
          

          
              <div class="post-description">
                  今天,准备填完昨天没填的坑,将排序算法方面的知识系统的学习一下,但是在简单的了解了一下后,有些不知如何组织学习了,因为排序算法的种类,实在是太多了,各有优略,各有适用的场景.有些不知所措,从何开始.
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><em>今天,准备填完昨天没填的坑,将排序算法方面的知识系统的学习一下,但是在简单的了解了一下后,有些不知如何组织学习了,因为排序算法的种类,实在是太多了,各有优略,各有适用的场景.有些不知所措,从何开始.</em></p>
<hr>
<p>最后按照常规思路,我将逐次从排序算法的了解,常用的几种排序算法的原理及实现,几种算法的对比以及适用场景.三个方面展开对排序算法的学习.</p>
<ul>
<li><strong>排序算法的基本了解</strong><br>在我们学习一样知识,技术之前,首先我们应当对它有一个基本的了解,然后在了解的基础上逐渐深入学习.</li>
</ul>
<blockquote>
<p>在计算机科学与数学中，排序算法（Sorting algorithm）是一种能将一串数据依照特定排序方式进行排列的一种算法。最常用到的排序方式是数值顺序以及字典顺序。有效的排序算法在一些算法例如搜索算法与合并算法中是重要的.基本上，排序算法的输出必须遵守下列两个原则：</p>
<ol>
<li>输出结果为递增序列（递增是针对所需的排序顺序而言）</li>
<li>输出结果是原输入的一种排列、或是重组</li>
</ol>
</blockquote>
<p>而在计算机科学种关于排序算法的分类,也十分有趣,是直接按照排序算法的性能分类的,而排序算法的性能又是以<strong>时间复杂度</strong>,<strong>空间复杂度</strong>来判断的,而在排序算法中,主要被考虑到的当然就是时间复杂度了,毕竟一组数据的排序快慢是可以很直观的影响到其性能的.</p>
<ul>
<li>时间复杂度与空间复杂度<br>时间复杂度,就是一个定性描述算法执行时间的函数.空间复杂度是对一个算法在运行过程中临时占用存储空间大小的量度.</li>
</ul>
<p><em>由于时间复杂度的定义比较难以使人理解,我将另写一篇文章,全面总结和学习一下时间复杂度和空间复杂度的相关知识,这里就不大篇幅的来进行说明了.</em></p>
<p> ###几种常用的排序算法的探讨<br>  排序算法是真的有很多,</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-f8ccb3215bc1d12b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-6-01.png"></p>
<p>经过选择,在这里选取其中最常使用到的6种排序算法进行探讨,关于一些较特殊的,高级的算法在之后需要使用到的时候再去学习.</p>
<ul>
<li>最基本的冒泡,选择,插入排序</li>
<li>进阶级别的希尔,归并,快速排序</li>
</ul>
<hr>
<ul>
<li>####算法的实现原理</li>
<li><strong>冒泡排序</strong><br>冒泡排序,作为最简单的最基础的排序方法,被广为人知,其是在排序算法问题之初就自然而然使人想到并运用到的排序算法,可以称之为排序算法的基础.<br>其算法思路是通过循环不断对比相邻的两个数据,使小的向前,大的向后,两者交换,较小的数像气泡一样不断上浮,最终完成排序,因此形象的称之为冒泡排序.<br><img src="http://upload-images.jianshu.io/upload_images/8067684-1df19b8c4a8ce91e.gif?imageMogr2/auto-orient/strip" alt="冒泡排序"></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 冒泡排序</span><br><span class="line">    * 通过两个for循环来排序数组</span><br><span class="line">    * 外层循环控制需要循环的轮次</span><br><span class="line">    * 内层循环控制相邻元素的对比及交换.</span><br><span class="line">    */</span><br><span class="line">   public void BubbleSort(int[] arr)&#123;</span><br><span class="line">       long startime = System.nanoTime(); // 记录程序开始运行的时间点</span><br><span class="line">       for (int i=1;i&lt;arr.length;i++)&#123; // 外层for循环</span><br><span class="line">           for (int j=0;j&lt;arr.length-i;j++)&#123; //内层for循环,arr.length-i表示每进行完一轮就将循环对比的的次数减小一次,因为最后面的顺序都是每次循环中最大的,顺序已经排好,不需要再进行对比了.</span><br><span class="line">               if (arr[j]&gt;arr[j+1])&#123;  //判断交换的条件,如果当前元素比后一个元素大就交换两者位置 </span><br><span class="line">                   int a=arr[j+1];  // 两个数的交换代码</span><br><span class="line">                   arr[j+1]=arr[j];</span><br><span class="line">                   arr[j]=a;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       System.out.println(Arrays.toString(arr));</span><br><span class="line">       long endtime = System.nanoTime(); // 记录程序结束的时间点</span><br><span class="line">       System.out.println(&quot;运行时间:&quot;+(endtime-startime)+&quot;ns&quot;); // 输出程序运行的时间(开始结束的时间差)</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>选择排序<br>选择排序算法思想是在末未排序的序列中找到最小的一个元素,然后和当前的首位元素交换位置,之后在循环在未排序的序列中找到最小的元素,将其插入到已排序的末尾位置.<br><img src="http://upload-images.jianshu.io/upload_images/8067684-a9b95c7a5b6a1942.gif?imageMogr2/auto-orient/strip" alt="选择排序"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 选择排序</span><br><span class="line">    * 选择排序也是通过两个for循环来实现的</span><br><span class="line">    * 外层for循环控制循环轮次,总共n-1轮</span><br><span class="line">    * 此外我们还需要声明一个局部变量记录每次循环对比的最小元素的下标.</span><br><span class="line">    * 内存for循环,通过依次对比比较,将当前未排序的序列中最小元素的下标记录下来.</span><br><span class="line">    *最后通过if判断找到的下标与最开始的下标i是否相同,不相同就交换两者对应的元素</span><br><span class="line">    */</span><br><span class="line">   public void Selectsort(int[] arr)&#123;</span><br><span class="line">       System.out.println(&quot;选择排序:&quot;);</span><br><span class="line">       long startime = System.nanoTime();</span><br><span class="line">       for(int i=0;i&lt;arr.length-1;i++)&#123; // 控制循环的轮次,总共需要n-1次.</span><br><span class="line">           int min =i; // 声明成员变量,用来储存最小元素的下标.</span><br><span class="line">           for(int j=i+1;j&lt;arr.length;j++)&#123; // 内层for循环,j=i+1是为了将序列分开为i表示的已排列,和i+1及之后的未排列两部分,</span><br><span class="line">               if(arr[j]&lt;arr[min])&#123;  // 判断条件,在未排列(即i+1之后的序列.)序列里找到最小元素</span><br><span class="line">                   min =j; // 将最小元素的下标保存到成员变量min中</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">           if(min !=i)&#123;  // 判断条件,判断最小元素是否和当前首位元素相同,</span><br><span class="line">               // 交换位置.</span><br><span class="line">               int a=arr[i];  </span><br><span class="line">               arr[i]=arr[min];</span><br><span class="line">               arr[min]=a;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       System.out.println(Arrays.toString(arr)); // Arrays类的toAString方法,遍历输出数组</span><br><span class="line">       long endtime=System.nanoTime();</span><br><span class="line">       System.out.println(&quot;运行时间:&quot;+(endtime-startime)+&quot;ns&quot;);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>插入排序<br>插入排序的算法思路也是将序列分为已排序和未排序两部分,然后从未排序的首位开始,依次和已排序的每个元素对比,大于或等于就插在该元素后一位,小于就插入到该元素前一位.插入排序是最容易理解的排序方法,其就像我们打扑克是的插牌一样.<br><img src="http://upload-images.jianshu.io/upload_images/8067684-30399c0701a1b5f8.gif?imageMogr2/auto-orient/strip" alt="插入排序"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">   * 插入排序</span><br><span class="line">   *插入排序也是通过嵌套循环实现排序的.</span><br><span class="line">   * y原始案例通过for,while循环嵌套实现,</span><br><span class="line">   */</span><br><span class="line">  public void Insertsort(int[] arr)&#123;</span><br><span class="line">      long startime=System.nanoTime();</span><br><span class="line">      System.out.println(&quot;插入排序:&quot;);</span><br><span class="line">      int[] copyarr=Arrays.copyOf(arr,23); // 复制数组,以防改变了数组arr.</span><br><span class="line">      for (int i=1;i&lt;copyarr.length;i++)&#123; //外层循环控制轮次.</span><br><span class="line">          int tmp=copyarr[i]; //将当前未排序的序列首位元素抽出.</span><br><span class="line">          int j=i-1; // 定义局部变量 j代表i前面的已排序序列的末位</span><br><span class="line">         while(j&gt;=0 &amp;&amp; copyarr[j]&gt;tmp)&#123; // while循环控制,从已排序末位逐渐往前对比,如果比tmp大.</span><br><span class="line">             copyarr[j+1]=copyarr[j]; //就交换两者值,</span><br><span class="line">             j--; // j自减一,实现循环比较交换,排序</span><br><span class="line">         &#125;</span><br><span class="line">          copyarr[j+1]=tmp; // 其他条件下,说明tmp就是当前的最小值,直接将tmp赋值给copyarr[j+1].</span><br><span class="line">      &#125;</span><br><span class="line">      System.out.println(Arrays.toString(copyarr));</span><br><span class="line">      long endtime=System.nanoTime();</span><br><span class="line">      System.out.println(&quot;运行时间:&quot;+(endtime-startime)+&quot;ns&quot;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>冒泡排序,选择排序,插入排序,都是最早,最简单演变下的排序算法,其时间复杂度相同,是最慢的排序算法,其在循环上进行了太多的重复性,无意义的循环操作.</p>
<ul>
<li>希尔排序<br>希尔排序也是一种递增减量算法,是插入排序的更高效的版本.希尔排序主要根据插入排序的两点改进的:<ul>
<li>当插入排序在处理趋近于正序的的序列时,效率最高,可以趋近于线性排序的效率.</li>
<li>插入排序每次只对一个数据进行操作移动,无疑使其效率低化.</li>
</ul>
</li>
</ul>
<p>希尔排序的基本思路:先将待排序列分为若干个子序列,再分别使用插入排列.在基本有序之后,再全部序列进行插入排列.也就是分组插入排列加插入排列.</p>
<p><img src="http://upload-images.jianshu.io/upload_images/8067684-efe0b0138af44107.gif?imageMogr2/auto-orient/strip" alt="希尔排列"><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 希尔排列</span><br><span class="line"> * 希尔排列是插入排列的进阶版</span><br><span class="line"> * 相当于将无序序列分成为多个子级无序序列,再分别进行插入排列.</span><br><span class="line"> */</span><br><span class="line">public void Shellsort(int[] arr) &#123;</span><br><span class="line">    long startime = System.nanoTime();</span><br><span class="line">    System.out.println(&quot;希尔排序:&quot;);</span><br><span class="line">    int[] copyarr = Arrays.copyOf(arr, 23);</span><br><span class="line">    for (int gap = copyarr.length / 2; gap &gt; 0; gap /= 2) &#123; // for循环控制分组情况,每次循环将序列拆分为两组直到不能拆分为止.</span><br><span class="line">        for (int j = gap; j &lt; copyarr.length; j++) &#123; //然后通过for循环控制每组无序序列直接进行插入排序</span><br><span class="line">            int temp = copyarr[j];</span><br><span class="line">            int k;</span><br><span class="line">            for (k = j - gap; k &gt;= 0 &amp;&amp; copyarr[k] &gt; temp; k -= gap) &#123;</span><br><span class="line">                copyarr[k + gap] = copyarr[k];</span><br><span class="line">            &#125;</span><br><span class="line">            copyarr[k + gap] = temp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(Arrays.toString(copyarr));</span><br><span class="line">    long endtime = System.nanoTime();</span><br><span class="line">    System.out.println(&quot;运行时间:&quot; + (endtime - startime) + &quot;ns&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>归并排序<br>归并排序（Merge sort）是建立在归并操作上的一种有效的排序算法。该算法是采用分治法（Divide and Conquer）的一个非常典型的应用。归并排序是一个十分高效的排序方法,并且其在任何情况下,时间复杂度都是相同的,但高效的同时,必然会牺牲一定的内存空间,由于归并排序需要一块额外的内存储存数组,所以可以说占用额外的内存空间是它唯一的缺点,这一点也注定了,它将不适合大型,大规模数据的排序.<br>其实现思路是,通过递归,或迭代的方式,将序列分成两个有序的序列,然后比较合并两个有序序列.合并两个有序序列是十分高效的.可以取景于O(n).<br><img src="http://upload-images.jianshu.io/upload_images/8067684-18bed0b197f975a4.gif?imageMogr2/auto-orient/strip" alt="归并排序"></li>
</ul>
<p>归并排序的原理图解:<br><img src="https://upload-images.jianshu.io/upload_images/8067684-a2d18a648ec93b88.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-7-01.png"></p>
<p>分,即通过递归不断分组,治,将排序好的分组合并.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * 归并排序</span><br><span class="line">     * 这里通过两个方法的调用实现.</span><br><span class="line">     * mergesort方法,主要将数组copy并分为左右两个序列.</span><br><span class="line">     * 通过调用本身实现不断的分化.</span><br><span class="line">     */</span><br><span class="line">    public int[] Mergesort(int[] arr)&#123;</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, arr.length);</span><br><span class="line">        if (copyarr.length&lt;2)&#123;</span><br><span class="line">            return copyarr;</span><br><span class="line">        &#125;</span><br><span class="line">        int middle =(int)Math.floor(copyarr.length / 2); // 将序列的长度一分为二.</span><br><span class="line">        int[] left = Arrays.copyOfRange(copyarr, 0, middle); </span><br><span class="line">        int[] right = Arrays.copyOfRange(copyarr, middle, copyarr.length);</span><br><span class="line">        // 返回值调用合并方法,将排序后的分组不断合并.最后返回一个完整的排序后的序列.</span><br><span class="line">        return merge(Mergesort(left),Mergesort(right));</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    protected int[] merge(int[] left, int[] right) &#123; //传参,将左右两个无序序列传进来.</span><br><span class="line">        int[] result = new int[left.length + right.length]; //定义一个新的空数组,长度为左右序列的长度之和,</span><br><span class="line"></span><br><span class="line">        int i = 0;  // 声明一个成员变量i.</span><br><span class="line"></span><br><span class="line">        while (left.length &gt; 0 &amp;&amp; right.length &gt; 0) &#123; // while 循环控制条件</span><br><span class="line">            if (left[0] &lt;= right[0]) &#123;  // if判断语句,判断左右序列对应位置元素的大小.</span><br><span class="line">                result[i++] = left[0]; // 然后将小的元素存放在合并数组的对应位置中.</span><br><span class="line">                left = Arrays.copyOfRange(left, 1, left.length);</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                result[i++] = right[0];</span><br><span class="line">                right = Arrays.copyOfRange(right, 1, right.length);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        while(left.length&gt;0)&#123; // 不满足以上while条件跳出循环时,执行,</span><br><span class="line">            result[i++] = left[0];</span><br><span class="line">            left = Arrays.copyOfRange(left,1,left.length);</span><br><span class="line">        &#125;</span><br><span class="line">        while(right.length&gt;0)&#123;</span><br><span class="line">            result[i++] = right[0];</span><br><span class="line">            right = Arrays.copyOfRange(right,1,right.length);</span><br><span class="line">        &#125;</span><br><span class="line">        return result; // 返回排序合并后的序列.</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>快速排序<blockquote>
<p>快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下，排序 n 个项目要 Ο(nlogn) 次比较。在最坏状况下则需要 Ο(n2) 次比较，但这种状况并不常见。事实上，快速排序通常明显比其他 Ο(nlogn) 算法更快，因为它的内部循环（inner loop）可以在大部分的架构上很有效率地被实现出来。</p>
</blockquote>
</li>
</ul>
<p>快速排序也是在分治思想上的又一经典的应用,在大部分情况下,快速排序总是最高效的,比归并排序还要高效的多,且其适用于大多所情况下,在无序的随机数排序上表现也要好的多,但同时它的缺点也很明显,它的时间按复杂并不固定,存在最坏情况,时间复杂度波动非常大,且其实现思路也是基于递归思想的,其空间复杂度会很高,占用额外的内存.</p>
<p>本质上,快速排序是在冒泡排序的基础上演变而来的分而治之的思想,其思路是:从序列中挑选一个基准值,将大于该数的数放在该基准的右边,小的放在左边,然后使用递归,依次将两边的序列排序.<br><img src="http://upload-images.jianshu.io/upload_images/8067684-495d11fd76ed4e9d.gif?imageMogr2/auto-orient/strip" alt="快速排序"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 快速排序</span><br><span class="line">    *快速排序是分而治之的经典应用之一</span><br><span class="line">    * 通过递归调用的方式实现排序,</span><br><span class="line">    * 在大多情况下,其效率是最高的.</span><br><span class="line">    */</span><br><span class="line">   public int[] sort(int[] arr)&#123; // sort 方法 用来出copy数组,并调用排序方法.</span><br><span class="line">       int[] copyarr=Arrays.copyOf(arr,arr.length);</span><br><span class="line">       return quicksort(copyarr,0,copyarr.length-1);</span><br><span class="line">   &#125;</span><br><span class="line">   // 快速排序方法.</span><br><span class="line">   private int[] quicksort(int[] arr,int left,int right)&#123; //传入参数,待排序的数组,左下标,及数组长度减1.</span><br><span class="line">       if(left&lt;right)&#123;  // if判断条件,这里没有else是因为left必然是小于right的.如果等于的话,直接返回数组就可以了.</span><br><span class="line">           int partitionindex = partition(arr,left,right); // 声明局部变量,调用分区方法,递归调用.</span><br><span class="line">           quicksort(arr,left,partitionindex-1); // </span><br><span class="line">           quicksort(arr,partitionindex+1,right); // 递归调用本身,</span><br><span class="line">       &#125;</span><br><span class="line">       return arr;</span><br><span class="line">   &#125;</span><br><span class="line">   /**</span><br><span class="line">    *     分区方法,将无序序列以基准为界分别放在左右两边,</span><br><span class="line">    *     真正的比较交换操作,是在这个分区方法里实现的.</span><br><span class="line">    *     然后在通过前面的递归调用,来循环使用分区方法,实现排序.</span><br><span class="line">    */</span><br><span class="line">   private int partition(int[] arr,int left,int right)&#123;</span><br><span class="line">       int pivot =left;</span><br><span class="line">       int index = pivot+1;</span><br><span class="line">       for (int i=index;i&lt;=right;i++)&#123;</span><br><span class="line">           if (arr[i]&lt;arr[pivot])&#123;</span><br><span class="line">               swap(arr,i,index);</span><br><span class="line">               index++;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       swap(arr,pivot,index-1);</span><br><span class="line">       return index-1;</span><br><span class="line">   &#125;</span><br><span class="line">   // 封装通用方法,将数组arr中的arr[i]与arr[j]的值交换</span><br><span class="line">   private void swap(int[] arr,int i,int j)&#123;</span><br><span class="line">       int temp = arr[i];</span><br><span class="line">       arr[i]=arr[j];</span><br><span class="line">       arr[j]=temp;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>源代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br></pre></td><td class="code"><pre><span class="line">package day_4_6;</span><br><span class="line">import java.util.Arrays;</span><br><span class="line">/**</span><br><span class="line"> * @outhor xiaoshe</span><br><span class="line"> * @date 2019/4/6  - @time 11:20</span><br><span class="line"> * 排序算法</span><br><span class="line"> */</span><br><span class="line">public class Sty_Sortalgrithm &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        int[] arr = &#123;5, 2, 4, 1, 3, 7, 9, 5, 6, 8, 0, 9, 10, 13, 11, 15, 12, 17, 14, 13, 18, 19, 20&#125;;</span><br><span class="line">        Sty_Sortalgrithm sortalgrithm = new Sty_Sortalgrithm();</span><br><span class="line">        sortalgrithm.BubbleSort(arr);</span><br><span class="line">        sortalgrithm.Selectsort(arr);</span><br><span class="line">        sortalgrithm.Insertsort(arr);</span><br><span class="line">        sortalgrithm.Shellsort(arr);</span><br><span class="line">        System.out.println(&quot;归并排序:&quot;);</span><br><span class="line">        System.out.println(Arrays.toString(sortalgrithm.Mergesort(arr)));</span><br><span class="line">        System.out.println(&quot;快速排序:&quot;);</span><br><span class="line">        System.out.println(Arrays.toString(sortalgrithm.sort(arr)));</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 冒泡排序</span><br><span class="line">     * 通过两个for循环来排序数组</span><br><span class="line">     * 外层循环控制需要循环的轮次</span><br><span class="line">     * 内层循环控制相邻元素的对比及交换.</span><br><span class="line">     */</span><br><span class="line">    public void BubbleSort(int[] arr) &#123;</span><br><span class="line">        long startime = System.nanoTime(); // 记录程序开始运行的时间点</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, 23);</span><br><span class="line">        System.out.println(&quot;冒泡排序:&quot;);</span><br><span class="line">        for (int i = 1; i &lt; copyarr.length; i++) &#123; // 外层for循环</span><br><span class="line">            for (int j = 0; j &lt; copyarr.length - i; j++) &#123; //内层for循环,arr.length-i表示每进行完一轮就将循环对比的的次数减小一次,因为最后面的顺序都是每次循环中最大的,顺序已经排好,不需要再进行对比了.</span><br><span class="line">                if (copyarr[j] &gt; copyarr[j + 1]) &#123;  //判断交换的条件,如果当前元素比后一个元素大就交换两者位置</span><br><span class="line">                    int a = copyarr[j + 1];  // 两个数的交换代码</span><br><span class="line">                    copyarr[j + 1] = copyarr[j];</span><br><span class="line">                    copyarr[j] = a;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Arrays.toString(copyarr)); // Arrays类中的toString方法遍历输出数组.</span><br><span class="line">        long endtime = System.nanoTime(); // 记录程序结束的时间点</span><br><span class="line">        System.out.println(&quot;运行时间:&quot; + (endtime - startime) + &quot;ns&quot;); // 输出程序运行的时间(开始结束的时间差)</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 选择排序</span><br><span class="line">     * 选择排序也是通过两个for循环来实现的</span><br><span class="line">     * 外层for循环控制循环轮次,总共n-1轮</span><br><span class="line">     * 此外我们还需要声明一个局部变量记录每次循环对比的最小元素的下标.</span><br><span class="line">     * 内存for循环,通过依次对比比较,将当前未排序的序列中最小元素的下标记录下来.</span><br><span class="line">     * 最后通过if判断找到的下标与最开始的下标i是否相同,不相同就交换两者对应的元素</span><br><span class="line">     */</span><br><span class="line">    public void Selectsort(int[] arr) &#123;</span><br><span class="line">        long startime = System.nanoTime();</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, 23);</span><br><span class="line">        System.out.println(&quot;选择排序:&quot;);</span><br><span class="line">        for (int i = 0; i &lt; copyarr.length - 1; i++) &#123; // 控制循环的轮次,总共需要n-1次.</span><br><span class="line">            int min = i; // 声明成员变量,用来储存最小元素的下标.</span><br><span class="line">            for (int j = i + 1; j &lt; copyarr.length; j++) &#123; // 内层for循环,j=i+1是为了将序列分开为i表示的已排列,和i+1及之后的未排列两部分,</span><br><span class="line">                if (copyarr[j] &lt; copyarr[min]) &#123;  // 判断条件,在未排列(即i+1之后的序列.)序列里找到最小元素</span><br><span class="line">                    min = j; // 将最小元素的下标保存到成员变量min中</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            if (min != i) &#123;  // 判断条件,判断最小元素是否和当前首位元素相同,</span><br><span class="line">                // 交换位置.</span><br><span class="line">                int a = copyarr[i];</span><br><span class="line">                copyarr[i] = copyarr[min];</span><br><span class="line">                copyarr[min] = a;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Arrays.toString(copyarr)); // Arrays类的toAString方法,遍历输出数组</span><br><span class="line">        long endtime = System.nanoTime();</span><br><span class="line">        System.out.println(&quot;运行时间:&quot; + (endtime - startime) + &quot;ns&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 插入排序</span><br><span class="line">     * 插入排序也是通过嵌套循环实现排序的.</span><br><span class="line">     * y原始案例通过for,while循环嵌套实现,</span><br><span class="line">     */</span><br><span class="line">    public void Insertsort(int[] arr) &#123;</span><br><span class="line">        long startime = System.nanoTime();</span><br><span class="line">        System.out.println(&quot;插入排序:&quot;);</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, 23); // 复制数组,以防改变了数组arr.</span><br><span class="line">        for (int i = 1; i &lt; copyarr.length; i++) &#123; //外层循环控制轮次.</span><br><span class="line">            int temp = arr[i]; // 声明temp,将此时未排序的首位元素抽出.</span><br><span class="line">            int j;</span><br><span class="line">            for (j = i - 1; j &gt;= 0 &amp;&amp; copyarr[j] &gt; temp; j--) &#123; // 内存for循环和判断条件合并.</span><br><span class="line">                //当无序序列首位元素(temp)小于有序序列末尾元素(copyarr[j])时</span><br><span class="line">                //就将j的值赋给j+1,这里的j+1=i;之所以使用j+1是为了能够在条件不满足时在内层for循环中循环进行判断.</span><br><span class="line">                copyarr[j + 1] = copyarr[j];</span><br><span class="line">            &#125;</span><br><span class="line">            copyarr[j + 1] = temp;  //在外层循环其他条件下,直接将temp赋值给j+1</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Arrays.toString(copyarr));</span><br><span class="line">        long endtime = System.nanoTime();</span><br><span class="line">        System.out.println(&quot;运行时间:&quot; + (endtime - startime) + &quot;ns&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 希尔排序</span><br><span class="line">     * 希尔排列是插入排列的进阶版</span><br><span class="line">     * 相当于将无序序列分成为多个子级无序序列,再分别进行插入排列.</span><br><span class="line">     */</span><br><span class="line">    public void Shellsort(int[] arr) &#123;</span><br><span class="line">        long startime = System.nanoTime();</span><br><span class="line">        System.out.println(&quot;希尔排序:&quot;);</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, 23);</span><br><span class="line">        for (int gap = copyarr.length / 2; gap &gt; 0; gap /= 2) &#123; // for循环控制分组情况,每次循环将序列拆分为两组直到不能拆分为止.</span><br><span class="line">            for (int j = gap; j &lt; copyarr.length; j++) &#123; //然后通过for循环控制每组无序序列直接进行插入排序</span><br><span class="line">                int temp = copyarr[j];</span><br><span class="line">                int k;</span><br><span class="line">                for (k = j - gap; k &gt;= 0 &amp;&amp; copyarr[k] &gt; temp; k -= gap) &#123;</span><br><span class="line">                    copyarr[k + gap] = copyarr[k];</span><br><span class="line">                &#125;</span><br><span class="line">                copyarr[k + gap] = temp;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Arrays.toString(copyarr));</span><br><span class="line">        long endtime = System.nanoTime();</span><br><span class="line">        System.out.println(&quot;运行时间:&quot; + (endtime - startime) + &quot;ns&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 归并排序</span><br><span class="line">     * 这里通过两个方法的调用实现.</span><br><span class="line">     * mergesort方法,主要将数组copy并分为左右两个序列.</span><br><span class="line">     * 通过调用本身实现不断的分化.</span><br><span class="line">     */</span><br><span class="line">    public int[] Mergesort(int[] arr)&#123;</span><br><span class="line">        int[] copyarr = Arrays.copyOf(arr, arr.length);</span><br><span class="line">        if (copyarr.length&lt;2)&#123;</span><br><span class="line">            return copyarr;</span><br><span class="line">        &#125;</span><br><span class="line">        int middle =(int)Math.floor(copyarr.length / 2); // 将序列的长度一分为二.</span><br><span class="line">        int[] left = Arrays.copyOfRange(copyarr, 0, middle);</span><br><span class="line">        int[] right = Arrays.copyOfRange(copyarr, middle, copyarr.length);</span><br><span class="line">        // 返回值调用合并方法,将排序后的分组不断合并.最后返回一个完整的排序后的序列.</span><br><span class="line">        return merge(Mergesort(left),Mergesort(right));</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    protected int[] merge(int[] left, int[] right) &#123; //传参,将左右两个无序序列传进来.</span><br><span class="line">        int[] result = new int[left.length + right.length]; //定义一个新的空数组,长度为左右序列的长度之和,</span><br><span class="line">        int i = 0;  // 声明一个成员变量i.</span><br><span class="line">        while (left.length &gt; 0 &amp;&amp; right.length &gt; 0) &#123; // while 循环控制条件</span><br><span class="line">            if (left[0] &lt;= right[0]) &#123;  // if判断语句,判断左右序列对应位置元素的大小.</span><br><span class="line">                result[i++] = left[0]; // 然后将小的元素存放在合并数组的对应位置中.</span><br><span class="line">                left = Arrays.copyOfRange(left, 1, left.length);</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                result[i++] = right[0];</span><br><span class="line">                right = Arrays.copyOfRange(right, 1, right.length);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        while(left.length&gt;0)&#123; // 不满足以上while条件跳出循环时,执行,</span><br><span class="line">            result[i++] = left[0];</span><br><span class="line">            left = Arrays.copyOfRange(left,1,left.length);</span><br><span class="line">        &#125;</span><br><span class="line">        while(right.length&gt;0)&#123;</span><br><span class="line">            result[i++] = right[0];</span><br><span class="line">            right = Arrays.copyOfRange(right,1,right.length);</span><br><span class="line">        &#125;</span><br><span class="line">        return result; // 返回排序合并后的序列.</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 快速排序</span><br><span class="line">     *快速排序是分而治之的经典应用之一</span><br><span class="line">     * 通过递归调用的方式实现排序,</span><br><span class="line">     * 在大多情况下,其效率是最高的.</span><br><span class="line">     */</span><br><span class="line">    public int[] sort(int[] arr)&#123; // sort 方法 用来出copy数组,并调用排序方法.</span><br><span class="line">        int[] copyarr=Arrays.copyOf(arr,arr.length);</span><br><span class="line">        return quicksort(copyarr,0,copyarr.length-1);</span><br><span class="line">    &#125;</span><br><span class="line">    // 快速排序方法.</span><br><span class="line">    private int[] quicksort(int[] arr,int left,int right)&#123; //传入参数,待排序的数组,左下标,及数组长度减1.</span><br><span class="line">        if(left&lt;right)&#123;  // if判断条件,这里没有else是因为left必然是小于right的.如果等于的话,直接返回数组就可以了.</span><br><span class="line">            int partitionindex = partition(arr,left,right); // 声明局部变量,调用分区方法,递归调用.</span><br><span class="line">            quicksort(arr,left,partitionindex-1); //</span><br><span class="line">            quicksort(arr,partitionindex+1,right); // 递归调用本身,</span><br><span class="line">        &#125;</span><br><span class="line">        return arr;</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     *     分区方法,将无序序列以基准为界分别放在左右两边,</span><br><span class="line">     *     真正的比较交换操作,是在这个分区方法里实现的.</span><br><span class="line">     *     然后在通过前面的递归调用,来循环使用分区方法,实现排序.</span><br><span class="line">     */</span><br><span class="line">    private int partition(int[] arr,int left,int right)&#123;</span><br><span class="line">        int pivot =left;</span><br><span class="line">        int index = pivot+1;</span><br><span class="line">        for (int i=index;i&lt;=right;i++)&#123;</span><br><span class="line">            if (arr[i]&lt;arr[pivot])&#123;</span><br><span class="line">                swap(arr,i,index);</span><br><span class="line">                index++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        swap(arr,pivot,index-1);</span><br><span class="line">        return index-1;</span><br><span class="line">    &#125;</span><br><span class="line">    // 封装通用方法,将数组arr中的arr[i]与arr[j]的值交换</span><br><span class="line">    private void swap(int[] arr,int i,int j)&#123;</span><br><span class="line">        int temp = arr[i];</span><br><span class="line">        arr[i]=arr[j];</span><br><span class="line">        arr[j]=temp;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>####算法的比较与使用<br>关于个排序算法的复杂度,稳定性,等信息的对比,可以参照下面这张图:</p>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-22a7e96231e8ef1b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-7-02.png"></p>
<p>根据前面的学些了解的特性,最基本的三种排序,冒泡,选择,插入排序,在小规模数据的排序上,表现会好些,在序列趋近于正序时,冒泡和插入更高效,.</p>
<p>归并排序是最稳定的排序算法,其在不同情况下的时间复杂度不会有多大变化,而在对大量无序随机数排序时,快排的效率时最高的,但,归并排序和快速排序对内存有一定要求,不适合需要控制内存使用的情况.</p>
<ul>
<li>参考:<br><a href="[https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95](https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95">排序算法–维基</a><br>)<br><a href="[http://www.runoob.com/w3cnote/ten-sorting-algorithm.html](http://www.runoob.com/w3cnote/ten-sorting-algorithm.html">十大经典排序算法</a><br>)<br><a href="[https://blog.csdn.net/ithomer/article/details/5636226](https://blog.csdn.net/ithomer/article/details/5636226">常见排序算法的稳定性分析与结论</a><br>)<br><a href="[https://zh.wikipedia.org/wiki/%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6](https://zh.wikipedia.org/wiki/%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6">时间复杂度</a><br>)</li>
</ul>
<hr>
<p>更新时间:<br>2019-4-7<br>3:14</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你现在可以打赏本宝宝啦！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixing.png" alt="葛木小舍先生 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zhifubao.png" alt="葛木小舍先生 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/gmxs/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/gmxs/2019/04/05/java初探/数组/" rel="next" title="Java数组">
                <i class="fa fa-chevron-left"></i> Java数组
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/gmxs/2019/04/07/java初探/关于时间复杂度/" rel="prev" title="关于时间复杂度与空间复杂度">
                关于时间复杂度与空间复杂度 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTg1Ni8xMjM5Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/gmxs/images/touxiang.png"
                alt="葛木小舍先生" />
            
              <p class="site-author-name" itemprop="name">葛木小舍先生</p>
              <p class="site-description motion-element" itemprop="description">不管过去过的如何，现在活的如何，将来将会如何。努力做好自己，朝梦想中的自己努力前进。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/gmxs/archives/">
              
                  <span class="site-state-item-count">61</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/gmxs/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/gmxs/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/gmxs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gemuxiaoshe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MaYaPeng2017@outlook.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5967971229/home?wvr=5&sudaref=graph.qq.com" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                个人收集站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gemumiaoshe.wordpress.com/" title="葛木小舍先生的小世界" target="_blank">葛木小舍先生的小世界</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.w3cschool.cn/html/" title="W3Cschool" target="_blank">W3Cschool</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="web前端导航" target="_blank">web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.itcast.cn/" title="传智播客" target="_blank">传智播客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://5sing.kugou.com/index.html" title="5sing" target="_blank">5sing</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.mikecrm.com/login.php?s=2&d=form.php#/list/" title="麦客CRM" target="_blank">麦客CRM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.51cto.com/" title="51CTO" target="_blank">51CTO</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">葛木小舍先生</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共111.1k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/gmxs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/gmxs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/gmxs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/gmxs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/gmxs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/gmxs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/gmxs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
